package com.neusoft.neuiotms.dcam.fixed.converter;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcam.fixed.dto.GoodsFileDTO;
import com.neusoft.neuiotms.dcam.fixed.model.GoodsFile;
import com.neusoft.neuiotms.dcam.fixed.repository.GoodsFileRepository;
import com.neusoft.neuiotms.dcam.fixed.repository.SpareTypeRepository;
import com.neusoft.neuiotms.dcam.fixed.vo.GoodsFileImportVO;

@Component
public class GoodsFileConverter extends AbstractConverter<GoodsFile, GoodsFileDTO> {

    @Autowired
    private GoodsFileRepository goodsFileRepository;

    @Autowired
    private SpareTypeRepository spareTypeRepository;

    @Override
    public GoodsFile toModel(final GoodsFileDTO dto) {
        final GoodsFile model;
        if (dto.isNew()) {
            model = new GoodsFile();
        } else {
            model = this.goodsFileRepository.getOne(dto.getId());
        }
        model.setName(dto.getName());
        model.setSpecification(dto.getSpecification());
        model.setDescription(dto.getDescription());
        model.setUpdateTime(new Date());

        if (dto.getSpareTypeCode() != null) {
            model.setSpareType(this.spareTypeRepository.findByCode(dto.getSpareTypeCode()));
        }
        return model;
    }

    @Override
    public GoodsFileDTO toDTO(final GoodsFile model, final boolean forListView) {
        final GoodsFileDTO dto = new GoodsFileDTO();

        dto.setId(model.getId());
        dto.setName(model.getName());
        dto.setSpecification(model.getSpecification());
        dto.setDescription(model.getDescription());
        dto.setCreateTime(model.getCreateTime());
        dto.setUpdateTime(model.getUpdateTime());
        if (model.getSpareType() != null) {
            dto.setSpareTypeCode(model.getSpareType().getCode());
            dto.setSpareTypeName(model.getSpareType().getName());
            dto.setMeasureUnit(model.getSpareType().getUnit());
            dto.setParentAssetTypeName(model.getSpareType().getParent().getName());
        }
        return dto;
    }

    public GoodsFile toModel(final GoodsFileImportVO goodsFile) {
        final GoodsFile model = new GoodsFile();
        model.setName(goodsFile.getName());
        model.setSpecification(goodsFile.getSpecification());
        model.setDescription(goodsFile.getDescription());
        model.setUpdateTime(new Date());
        return model;
    }

    public GoodsFileImportVO toVO(final GoodsFile model) {
        final GoodsFileImportVO vo = new GoodsFileImportVO();
        vo.setName(model.getName());
        vo.setSpecification(model.getSpecification());
        vo.setSpareTypeName(model.getSpareType().getName());
        vo.setDescription(model.getDescription());
        return vo;
    }

}
